package com.utilities;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	/**
	 * 
	 * @Title get
	 * @Description 获得Cookie中键的值
	 * @param request HttpServletRequest对象
	 * @param key     Cookie中的键名称
	 * @return 返回类型 String,即Cookie中键的值
	 */
    public static String get(HttpServletRequest request,String key) {
    	   Cookie[] allCookies=request.getCookies();
			if(allCookies!=null){
				for (int i = 0; i < allCookies.length; i++) {
					String itemName=allCookies[i].getName();
					String itemValue=allCookies[i].getValue();
					if(itemName.equals(key)){
						try {
							return URLDecoder.decode(itemValue,"UTF-8");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}
				}
				return null;
			}
		return null;
	}
    public static void set(HttpServletResponse response,String key,String value,int expireSeconds) {
    	    Cookie userCookie;
			try {
				userCookie = new Cookie(key,URLEncoder.encode(value,"UTF-8"));
				userCookie.setMaxAge(expireSeconds);
				response.addCookie(userCookie);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
	}
    public static void unSet(HttpServletRequest request,HttpServletResponse response, String key) {
 	   Cookie[] allCookies=request.getCookies();
			if(allCookies!=null){
				for (int i = 0; i < allCookies.length; i++) {
					Cookie item=allCookies[i];
					if(item.getName().equals(key)){
						item.setMaxAge(0);
						response.addCookie(item);
					}
				}
			}
	}
    public static void clear(HttpServletRequest request,HttpServletResponse response) {
  	   Cookie[] allCookies=request.getCookies();
 			if(allCookies!=null){
 				for (int i = 0; i < allCookies.length; i++) {
 				     allCookies[i].setMaxAge(0);
 				     response.addCookie(allCookies[i]);
 				}
 			}
 	}
}
